package com.ktjy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjy.dto.UserDTO;
import com.ktjy.mapper.SysUserPostMapper;
import com.ktjy.mapper.SysUserRoleMapper;
import com.ktjy.pojo.SysDept;
import com.ktjy.pojo.SysUser;
import com.ktjy.mapper.SysUserMapper;
import com.ktjy.pojo.SysUserPost;
import com.ktjy.pojo.SysUserRole;
import com.ktjy.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author jjx
 * @since 2025-07-28
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    SysUserRoleMapper sysUserRoleMapper;
    @Resource
    SysUserPostMapper sysUserPostMapper;

    @Override
    public SysUser login(String userName, String password) {
        QueryWrapper qw=new QueryWrapper();
        qw.eq("user_name",userName);
        SysUser sysUser = sysUserMapper.selectOne(qw);
        if(sysUser!=null){
            if(sysUser.getPassword().equals(password)){
                return sysUser;
            }
        }
        return null;
    }

    @Override
    public IPage<SysUser> findPage(UserDTO userDTO,
                                   Integer pageNo, Integer pageSize) {
        //构造分页条件
        Page page=new Page(pageNo,pageSize);
        return sysUserMapper.selectPage(page,userDTO);
    }

    @Override
    public boolean checkNameUnique(String name) {
        //查询数据
        QueryWrapper<SysUser> qw=new QueryWrapper<>();
        qw.eq("user_name",name);
        return count(qw)>0;
    }


    @Override
    public void saveOrUpdateUser(SysUser sysUser) {
        Long userId=sysUser.getUserId();
        //保存用户信息
        this.saveOrUpdate(sysUser);

        if(userId!=null){//说明是修改
            //先删除用户对应的角色
            QueryWrapper roleQw=new QueryWrapper();
            roleQw.eq("user_id",sysUser.getUserId());
            sysUserRoleMapper.delete(roleQw);
        }
        //批量新增用户对应角色信息
        batchInsertUserRole(sysUser.getRoleIds(), sysUser.getUserId());
        if(userId!=null){//说明是修改
            //先删除用户对应的角色
            QueryWrapper postQw=new QueryWrapper();
            postQw.eq("user_id",sysUser.getUserId());
            sysUserPostMapper.delete(postQw);
        }
        //批量新增用户对应岗位信息
        batchInsertUserPost(sysUser.getPostIds(), sysUser.getUserId());
    }

    @Override
    public SysUser findUser(Long userId) {
        //1.查询用户信息
        SysUser sysUser = this.getById(userId);

        //2.查询用户关联的岗位信息
        QueryWrapper<SysUserPost> postQw=new QueryWrapper<SysUserPost>();
        postQw.eq("user_id",sysUser.getUserId());
        List<SysUserPost> sysUserPosts = sysUserPostMapper.selectList(postQw);

        List<Long> postList = new ArrayList<Long>();
        for (SysUserPost sysUserPost : sysUserPosts) {
            postList.add(sysUserPost.getPostId());
        }
        sysUser.setPostIds(postList.toArray(new Long[0]));
        //3.查询用户关联的角色信息
        QueryWrapper<SysUserRole> roleQw=new QueryWrapper<SysUserRole>();
        roleQw.eq("user_id",sysUser.getUserId());
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(roleQw);

        List<Long> roleList = new ArrayList<Long>();
        for (SysUserRole sysUserrole : sysUserRoles) {
            roleList.add(sysUserrole.getRoleId());
        }
        sysUser.setRoleIds(roleList.toArray(new Long[0]));

        return sysUser;
    }

    @Override
    public void deleteUser(Long userId) {
        //1.删除用户对应的角色信息
        QueryWrapper<SysUserRole> roleQw=new QueryWrapper<SysUserRole>();
        roleQw.eq("user_id",userId);
        sysUserRoleMapper.delete(roleQw);
        //2.删除用户对应的岗位信息
        QueryWrapper<SysUserPost> postQw=new QueryWrapper<SysUserPost>();
        postQw.eq("user_id",userId);
        sysUserPostMapper.delete(postQw);
        //3.删除用户信息
        this.removeById(userId);
    }

    /**
     * 查询用户列表
     * @param userDTO
     * @return
     */
    @Override
    public List<SysUser> findList(UserDTO userDTO) {
        return sysUserMapper.findList(userDTO);
    }

    /**
     * 导出Excel
     * @param sheetName
     * @param list
     * @return
     */
    @Override
    public Workbook exportExcel(String sheetName, List<SysUser> list) {
        //创建工作簿
        Workbook workbook = new XSSFWorkbook();
        //创建工作表
        Sheet sheet = workbook.createSheet(sheetName);
        sheet.setColumnWidth(0,3000);
        sheet.setColumnWidth(1,3000);
        sheet.setColumnWidth(2,3000);
        sheet.setColumnWidth(3,3000);
        sheet.setColumnWidth(4,3000);
        sheet.setColumnWidth(5,3000);
        sheet.setColumnWidth(6,3000);
        //创建行
        //创建表头
        Row row = sheet.createRow(0);
        //创建列
        String[] titles = {"编号","用户姓名","账号","部门","手机号","状态","创建时间"};
        for (int i = 0; i < titles.length; i++){
            Cell cell = row.createCell(i);
            cell.setCellValue(titles[i]);
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //3.2创建数据行
        for (int i = 0; i < list.size(); i++) {
            SysUser sysUser = list.get(i);

            Row dataRow = sheet.createRow(i+1);

            Cell cell1 = dataRow.createCell(0);
            cell1.setCellValue(sysUser.getUserId());
            Cell cell2 = dataRow.createCell(1);
            cell2.setCellValue(sysUser.getRealName());
            Cell cell3 = dataRow.createCell(2);
            cell3.setCellValue(sysUser.getUserName());
            Cell cell4 = dataRow.createCell(3);
            cell4.setCellValue(sysUser.getDept().getDeptName());
            Cell cell5 = dataRow.createCell(4);
            cell5.setCellValue(sysUser.getPhonenumber());
            Cell cell6 = dataRow.createCell(5);
            cell6.setCellValue(sysUser.getStatus().equals("0")?"正常":"停用");
            Cell cell7 = dataRow.createCell(6);
            cell7.setCellValue(dateTimeFormatter.format(sysUser.getCreateTime()));
        }
        return workbook;
    }

    /**
     * 导入Excel数据
     * @param file
     * @return
     */
    @Override
    public List<SysUser> importExcel(MultipartFile file) {
        List<SysUser> list = new ArrayList<>();
        try {
            //1.将文件解析为Workbook对象
            Workbook workbook = new XSSFWorkbook(file.getInputStream());
            //2.获取工作表
            Sheet sheet = workbook.getSheetAt(0);
            //3.获取最后一行下标
            int lastRowNum = sheet.getLastRowNum();
            for(int i=1;i<=lastRowNum;i++){
                Row row = sheet.getRow(i);
                SysUser user=new SysUser();

                Cell cell1 = row.getCell(0);
                user.setUserId((long)cell1.getNumericCellValue());

                Cell cell2 = row.getCell(1);
                user.setRealName(cell2.getStringCellValue());

                Cell cell3 = row.getCell(2);
                user.setUserName(cell3.getStringCellValue());

                Cell cell4 = row.getCell(3);
                user.setDeptId((long)cell4.getNumericCellValue());

                Cell cell5 = row.getCell(4);
                cell5.setCellType(CellType.STRING);
                user.setPhonenumber(cell5.getStringCellValue());

                list.add(user);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    /**
     * 批量新增用户对应的角色
     * @param roles
     * @param userId
     */
    private void batchInsertUserRole(Long[] roles,Long userId){
        if (roles!=null && roles.length>0) {
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                sysUserRoleMapper.insert(list);
            }
        }
    }

    /**
     * 批量新增用户对应的岗位
     * @param postIds
     * @param userId
     */
    private void batchInsertUserPost(Long[] postIds,Long userId){
        if (postIds!=null && postIds.length>0) {
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : postIds) {
                SysUserPost up = new SysUserPost();
                up.setUserId(userId);
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                sysUserPostMapper.insert(list);
            }
        }
    }
}
